package com.etoak.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @Author by 孙有泽
 * @Date 2025/2/23 18:38
 * @Description
 */
@Component
@Data
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {
     private String secret;
     private String issuer;
     private int expiration;

     public String generateToken(Map<String,String> map){
         Calendar instance = Calendar.getInstance();
         instance.add(Calendar.MINUTE, expiration);
         JWTCreator.Builder builder = JWT.create();
         map.forEach((k,v)->{
             builder.withClaim(k,v);
         });
         String token= builder.withIssuer(issuer).withExpiresAt(new Date()).withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(secret));
        return token;
     }
     public boolean verify(String token){
         try {
             JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
         }catch (JWTVerificationException e){
             return false;
         }
         return true;
     }
     public DecodedJWT decodedJWT(String token){
         try{
             return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
         }catch (SignatureVerificationException e){
             throw new RuntimeException("无效签名");
         }catch (AlgorithmMismatchException e){
             throw new RuntimeException("算法不匹配");
         }catch (TokenExpiredException e){
             throw new RuntimeException("token已过期");
         }catch (Exception e){
             throw new RuntimeException("无效token");
         }
     }
}
